package cn.szabadsag.hrm.service.impl;

import cn.szabadsag.hrm.doc.CourseDoc;
import cn.szabadsag.hrm.dto.CourseParamDto;
import cn.szabadsag.hrm.mapper.HighlightResultMapper;
import cn.szabadsag.hrm.repository.CourseElasticsearchRepository;
import cn.szabadsag.hrm.service.ICourseElasticsearchService;
import cn.szabadsag.hrm.util.PageList;
import cn.szabadsag.hrm.vo.AggPageListVO;
import cn.szabadsag.hrm.vo.Bucket;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yangcong
 * @date 2022年04月10日 21:26
 * @since
 */
@Service
public class CourseElasticsearchServiceImpl implements ICourseElasticsearchService {

    @Autowired
    private CourseElasticsearchRepository repository;

    @Autowired
    private ElasticsearchRestTemplate template;

    @Autowired
    private HighlightResultMapper highlightResultMapper;

    /**
     * 保存课程到ES中
     * @param doc
     */
    @Override
    public void add(CourseDoc doc) {
        repository.save(doc);
    }

    /**
     * 从ES中删除课程
     * @param id
     */
    @Override
    public void delete(Long id) {
        repository.deleteById(id);
    }

    /**
     * 课程查询
     * @param dto
     * @return
     */
    @Override
    public AggPageListVO searchCourse(CourseParamDto dto) {
        //  创建搜索查询对象建造者
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //  分页==========================================================================
        builder.withPageable(PageRequest.of(dto.getPage()-1,dto.getRows()));
        //  排序==========================================================================
        String sortField = dto.getSortField();// 需要排序的字段
        if (StringUtils.isNotEmpty(sortField)){
            String sortFieldName = "price";
            switch (sortField){
                case "xl":
                    sortFieldName = "saleCount";
                    break;
                case "xp":
                    sortFieldName = "onlineTime";
                    break;
                case "pl":
                    sortFieldName = "commentCount";
                    break;
                case "jg":
                    sortFieldName = "price";
                    break;
                case "rq":
                    sortFieldName = "viewCount";
                    break;
            }
            SortOrder sortOrder = SortOrder.DESC;
            if (sortOrder != null && dto.getSortType().equalsIgnoreCase("asc")){
                sortOrder = SortOrder.ASC;
            }
            builder.withSort(new FieldSortBuilder(sortFieldName).order(sortOrder));
        }
        //  查询条件==========================================================================
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //  DSL查询
        if (StringUtils.isNotBlank(dto.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("name",dto.getKeyword()));
        }
        //  DSL过滤
        if (dto.getCourseTypeId() != null){
            //  课程分类id
            boolQueryBuilder.filter(QueryBuilders.termQuery("courseTypeId",dto.getCourseTypeId()));
        }
        if (StringUtils.isNotEmpty(dto.getGradeName())){
            //  课程等级名字
            boolQueryBuilder.filter(QueryBuilders.termQuery("gradeName", dto.getGradeName()));
        }
        if (dto.getPriceMax() != null){
            //  最高价格
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(dto.getPriceMax()));
        }
        if (dto.getPriceMin() != null){
            //  最低价格
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(dto.getPriceMax()));
        }
        if (StringUtils.isNotEmpty(dto.getTenantName())){
            //  机构名称
            boolQueryBuilder.filter(QueryBuilders.termQuery("tenantName", dto.getTenantName()));
        }
        //  DSL查询+过滤
        builder.withQuery(boolQueryBuilder);
        //  处理高亮==========================================================================
        HighlightBuilder.Field highlightField = new HighlightBuilder.Field("name")
                .preTags("<font style='color:red; font-size:15px'>")
                .postTags("</font>");
        builder.withHighlightFields(highlightField);

        //  处理聚合==========================================================================
        //  机构terms的聚合
        TermsAggregationBuilder tenantNameAgg = AggregationBuilders.terms("tenantNameAgg").field("tenantName");
        //  等级terms的聚合
        TermsAggregationBuilder gradeNameAgg = AggregationBuilders.terms("gradeNameAgg").field("gradeName");

        builder.addAggregation(tenantNameAgg).addAggregation(gradeNameAgg);
        //  创建搜索查询对象
        SearchQuery searchQuery = builder.build();
        //  执行搜索ES中的数据
        //Page<CourseDoc> courseDocPage = repository.search(searchQuery);
        AggregatedPage<CourseDoc> courseDocPage = template.queryForPage(searchQuery, CourseDoc.class, highlightResultMapper);
        //  处理聚合结果========================================================================
        Aggregations aggregations = courseDocPage.getAggregations();

        Map<String, Aggregation> aggregationMap = aggregations.asMap();

        //  封装结果集
        Map<String, List<Bucket>> aggs = new HashMap<>();
        aggregationMap.entrySet().forEach(entry -> {
            //  聚合的名字
            String key = entry.getKey();
            System.out.println("聚合的名字" + entry.getKey());

            List<Bucket> bucketList = new ArrayList<>();

            ParsedStringTerms entryValue = (ParsedStringTerms) entry.getValue();
            List<? extends Terms.Bucket> buckets = entryValue.getBuckets();
            buckets.forEach(bucket -> {
                String bucketKey = bucket.getKeyAsString();
                long docCount = bucket.getDocCount();
                System.out.println("bucketKey=" + bucketKey + "，docCount=" + docCount);

                bucketList.add(new Bucket(bucketKey,docCount));
            });
            aggs.put(key,bucketList);
        });

        //  返回分页数据
        return new AggPageListVO(courseDocPage.getTotalElements(),courseDocPage.getContent(),aggs);
    }
}
